<template>
  <div class="setup">
    <div class="box">
      <van-nav-bar title="账号设置" left-text="返回" left-arrow @click-left="back" />
      <div>
        <van-field size="large" name="uploader" label="上传头像">
          <template #input>
            <van-uploader deletable :max-count="1" :after-read="afterRead" v-model="fileList" />
          </template>
        </van-field>
        <van-field size="large" v-model="userForm.phone" label="手机号" />
        <van-field size="large" v-model="userForm.uname" label="用户名" />
        <van-field size="large" v-model="userForm.autograph" label="个性签名" />
      </div>
      <div class="box-bu">
        <van-button type="primary" size="large" color="#63c6c2" native-type="submit" @click="onSubmit">保存</van-button>
        <van-button type="primary" size="large" color="#63c6c2" to="Cipher">修改密码</van-button>
        <van-button type="primary" size="large" color="#63c6c2" @click="logOut">退出登录</van-button>
        <van-button type="primary" size="large" color="#63c6c2" @click="cancellation">注销账号</van-button>
      </div>
    </div>
  </div>
</template>
<script>
import { getUserInfo, updateUserInfo, deleteUser } from '../server/user.js';
export default {
  data() {
    return {
      token: localStorage.getItem('token'), //token
      // 信息表单
      userForm: {
        phone: '',
        uname: '',
        autograph: '',
        avatar: '',
      },
      // 头像预览
      fileList: [{ url: '', isImage: true, status: 'done' }],
      // 七牛token
      qiniuToken: '',
    };
  },
  mounted() {
    // 获取用户信息,自动填写到表单中
    getUserInfo(this.token)
      .then((result) => {
        this.userForm = result[0];
        this.fileList[0].url = this.userForm.avatar;
      })
      .catch((err) => {
        console.log(err);
      });
    // 获取七牛token
    this.axios.get('/qiniuToken').then((res) => {
      this.qiniuToken = res.data.result;
    });
  },
  methods: {
    back() {
      //事件绑定返回上个页面的一个函数
      this.$router.back();
    },
    afterRead(file) {
      file.status = 'uploading';
      file.message = '上传中...';

      let data = new FormData();
      data.append('file', file.file);
      data.append('token', this.qiniuToken);

      //发送请求,上传至图床平台
      this.axios({
        url: 'https://upload-z2.qiniup.com',
        method: 'post',
        data,
        headers: { 'Content-Type': 'multipart/form-data' },
      }).then((result) => {
        if (result.status == 200) {
          this.userForm.avatar = `http://liuchun1025.xyz/${result.data.key}`;
          file.status = 'done';
        } else this.$toast.file(`头像上传失败,请重试`);
      });
    },
    onSubmit() {
      // 验证手机号
      let regPhone = /^(?:(?:\+|00)86)?1[3-9]\d{9}$/;
      if (regPhone.test(this.userForm.phone) == false) {
        this.$toast.fail(`请输入正确的手机号`);
        return;
      }
      // 验证用户名
      let regUname = /^\w{5,16}$/;
      if (regUname.test(this.userForm.uname) == false) {
        this.$toast.fail(`请输入6-16位数字或字母的用户名`);
        return;
      }
      // 发送修改请求
      updateUserInfo(this.token, this.userForm)
        .then((result) => {
          if (result == 1) {
            this.$toast.success(`修改成功`);
            this.$router.push('/mine');
            return;
          } else {
            this.$toast.fail(`手机号已被使用`);
          }
        })
        .catch(() => {
          this.$toast.fail(`修改失败`);
          return;
        });
    },
    // 退出登录
    logOut() {
      localStorage.removeItem('token');
      this.$router.push('/');
    },
    //注销账号
    cancellation() {
      this.$dialog
        .confirm({
          title: '警告',
          message: '注销后无法恢复账号,确认注销吗',
        })
        .then(() => {
          deleteUser(this.token)
            .then(() => {
              localStorage.removeItem('token');
              this.$router.push('/');
              this.$toast.fail(`账号已注销`);
            })
            .catch(() => {
              this.$toast.fail('注销失败');
            });
        })
        .catch(() => {
          // on cancel
        });
    },
  },
};
</script>
<style lang="scss">
.setup {
  background-color: #f7f7f7;

  .van-icon-arrow-left {
    color: #000;
  }

  .van-nav-bar__text {
    font-size: 14px;
    color: #000;
  }

  .box {
    background-color: #fff;

    .box-bu {
      margin-top: 20px;

      & > .van-button--primary {
        margin-top: 10px;
        margin-bottom: 10px;
        width: 80%;
        margin-left: 10%;
      }
    }
  }
}
</style>
